import 'package:app/api/delivery/index.dart';
import 'package:app/api/material-pick/material.dart';
import 'package:app/components/index.dart';
import 'package:app/util/StringUtils.dart';
import 'package:flutter/material.dart';
import 'package:qrscan/qrscan.dart' as scanner;

class Relay extends StatefulWidget {
  const Relay({super.key});
  @override
  State<Relay> createState() => _Relay();
}

class _Relay extends State<Relay> {
  final FocusNode _firstFocusNode = FocusNode();
  String _code = "";
  final GlobalKey<FormState>? _formKey = GlobalKey<FormState>();
  List<dynamic> _data = [];

  @override
  void initState() {
    super.initState();
    // 在初始化时将焦点放在第一个文本框上
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_firstFocusNode);
    });
  }

  void hideKeyBorder() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  void scan() async{
    String? qrCode = await scanner.scan();
    setState(() => _code = qrCode.toString());
  }

  void setValue(String key, String value){
    switch(key){
      case '_code' :
        _code = value;
        break;
      default:
        throw Exception("key error");
    }
  }

  void go(String path){
    Navigator.pushNamed(context, path);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBars(context: context, title: '人工接力'),
      body: GestureDetector(
        onTap: hideKeyBorder,
        child: Container(
          color: const Color.fromARGB(255, 245, 245, 245),
          child: Column(
            children: [
              Group(
                title: '操作',
                height: 120,
                context: context,
                child: Menu(context: context, items: [
                  MenuItem(
                    icon: const Icon(Icons.add, color: Colors.white, size: 40),
                    text: "物料拣配",
                    color: const Color.fromARGB(255, 154, 204, 109),
                    onTap: () => go('/material-pick'),
                  ),
                  MenuItem(
                    icon: const Icon(Icons.call, color: Colors.white,size: 40),
                    text: "空托呼叫",
                    color: const Color.fromARGB(255, 109, 183, 234),
                    onTap: ()=>go('/empty-pallet-call'),
                  ),
                ]),
              ),
              Group(
                context: context,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Forms(
                      formKey: _formKey,
                      formItem: [
                        FormItem(
                          onEntry: (String value) => {confirm()},
                          type: 'input',
                          labelWidth: 90,
                          focusNode: _firstFocusNode,
                          placeholder: '请扫站点码',
                          labelText: '站点码',
                          filedName: 'code',
                          icon: const Icon(Icons.qr_code_scanner_rounded),
                          iconOnTap: scan,
                          value: _code,
                          onChange: (value) => setValue('_code', value),
                          rules: const {'code': [{'required': true, 'message': '站点码不能为空'}]},
                        )
                      ],
                    ),
                  ],
                ),
              ),
              Expanded(
                child: ListContainer(
                  title: '站点物料清单',
                  length: _data.length,
                  children: (index){
                    return[
                      ListTitle(
                        context: context,
                        label: _data[index]['itemName']
                      ),
                      Horizontal(items: [
                        HorizontalItem(
                          label: '物料编码：',
                          value: _data[index]['itemCode'],
                        ),
                        HorizontalItem(
                          label: '数量：',
                          value: _data[index]['itemQty'],
                          valueBackground: Colors.lightBlueAccent,
                          fontColor: Colors.white,
                        )
                      ],),
                      Horizontal(items: [
                        HorizontalItem(
                          label: '托盘号：',
                          value: _data[index]['container'],
                          valueBackground: Colors.green,
                          fontColor: Colors.white,
                        ),
                      ]),
                      Horizontal(items: [
                        HorizontalItem(
                          label: '流向：',
                          value: _data[index]['endLocationName'],
                        )
                      ]),
                    ];
                  },
                ),
              ),
              Container(
                width: MediaQuery.of(context).size.width,
                padding: const EdgeInsets.only(top: 10, left: 20, right: 20),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Expanded(
                      child: Button(
                        onPressed: createDelivery,
                        label: '接力配送',
                        height: 60,
                        fontSize: 18,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void clear(){
    setState(() {
      _code = "";
      _data = [];
    });
  }

  //查询站点物料清单
  void confirm(){
    MaterialApi.of(context).list(_code).then((res){
      if(StringUtils.isNotNull(res.data['data'])){
        setState((){
          _data = res.data['data'];
        });
      }else{
        showNoInventoryDialog(context);
      }
    });
  }

  //创建配送单
  void createDelivery(){
    Forms.validate(_formKey!).then((valid) {
      if(_data.isEmpty){
        Error.of(context).show('没有可配送的物料');
        return;
      }
      if (StringUtils.isNull(_data[0]['endLocationCode'])) {
        showNoEndStationDialog(context);
      } else {
        String pickId = _data[0]['pickId'];
        Confirm.of(context).show('确定要开始配送么', (){
          Delivery.of(context).immediately(pickId).then((res){
            Navigator.pop(context);
            if(StringUtils.isNotNull(res) && StringUtils.isNotNull(res.data)){
              Success.of(context).show('配送单创建成功，请等待');
            }
          });
        });
      }
    });
  }

  //无库存信息提示框
  void showNoInventoryDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('提示'),
          content: const Text('当前站点没有物料。'),
          actions: [
            TextButton(
              child: const Text('关闭'),
              onPressed: () {
                Navigator.of(context).pop();
                clear();
              },
            ),
          ],
        );
      },
    );
  }

  //无流向信息提示框
  void showNoEndStationDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('提示'),
          content: const Text('没有流向信息无法创建接力配送单。'),
          actions: [
            TextButton(
              child: const Text('关闭'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }
}
